<?php

namespace app\base\model\system;

use think\Model;
use app\core\cache\{RedisCache, RedisKeys};
use think\Request;
use think\Db;

class SystemAdminLoginLog extends Model
{

    // 关闭自动写入时间戳
    protected $autoWriteTimestamp = false;

    protected $table = 'xy_system.xy_system_admin_login_log';

    const WRITE_LOG_REDIS_KEY = 'admin_login_log:';

    /**
     * Desc: 管理员登录日志
     * Date: 2019/10/21 21:04
     * Author: yiyu
     * @param $admin_id
     * @return SystemAdminLoginLog
     */
    public static function insertAdminLoginLog($admin_id)
    {
        $data = [
            'admin_id' => $admin_id,
            'login_ip' => Request::instance()->ip(),
            'login_time' => date('Y-m-d H:i:s'),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        ];
        return self::create($data);
    }

    public static function writeAdminLoginLog($admin_id)
    {

        $key = RedisKeys::getWriteAdminLoginLogFlagKey($admin_id);
        if (!RedisCache::has($key)) {
            self::insertAdminLoginLog($admin_id);
            SystemAdmin::where('admin_id', $admin_id)->update([
                'login_count' => Db::raw('login_count+1'),
                'last_ip' => Request::instance()->ip(),
                'last_time' => date('Y-m-d H:i:s')
            ]);
            RedisCache::set($key, time(), 3600);
        }
    }
}